<template>
  <el-container style="height: 100%">
    <el-main>
      <el-row style="margin-bottom: 10px;">
        <el-col :span="5">
        </el-col>
        <el-col :span="10">
        </el-col>
        <el-col :span="9">
          <el-input
              v-model="queryParams.searchName"
              placeholder="请输入username"
          >
            <template #append>
              <el-button :icon="Search" @click="getList()" />
            </template>
          </el-input>
        </el-col>
      </el-row>

      <el-table :data="tableData" style="width: 100%" border>
        <el-table-column type="index" label="序号" width="60"/>
        <el-table-column prop="title" label="头像" width="180">
          <template #default="scope">
            <div style="display: flex;justify-content: center">
              <el-image style="width: 100px; height: 100px;display: flex;justify-content: center" :src="baseImageUrl+scope.row.username+'.jpg'"
                        :key="scope.row.id"
                        :hide-on-click-modal="true"
                        :fit="'fill'" >
                <template #error>
                  <img src=""
                  />
                </template>
              </el-image>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="username" label="用户名" width="180"/>
        <el-table-column prop="realName" label="姓名" width="180"/>
        <el-table-column prop="usergroup" label="分组">
          <template #default="scope">
            <el-select  @change=" a => itemchange(a,scope.row) " v-model="scope.row.usergroup"
                        placeholder="请选择分组" size="large">

              <el-option
                  v-for="item in groupData"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
              />
            </el-select>
          </template>
        </el-table-column>
      </el-table>
      <div class="page-div">
        <el-pagination
            v-show="total>0"
            v-model:currentPage="queryParams.pageNum"
            v-model:page-size="queryParams.pageSize"
            :page-sizes="[10,20,30,50]"
            :small="small"
            :disabled="disabled"
            :background="background"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
        />
      </div>
    </el-main>
    <el-aside width="260px" style="margin-top: 40px;">
      <el-menu
          :default-active="activeIndex"
          class="el-menu-demo"
          mode="vertical"
          @select="handleSelect"
      >
        <el-menu-item v-for="(item, index) in groupData" :key="item.id" :index="index+''">
          <div @mouseenter="menuItemMouseEnter(item)" @mouseleave="menuItemBlur(item)" style="display: flex;justify-content: space-between;width: 450px;">
            <span v-if="!item.showEdit">{{item.name}} ({{item.membersSize}})</span>
            <el-input @click.stop="item.showEdit=true" v-if="item.showEdit" v-model="item.name" placeholder="请输入分组名" @blur.stop="updateNewGroup(item)">
              <template #append>
                <el-button type="info" @click.stop="updateNewGroup(item)">保存</el-button>
              </template>
            </el-input>
            <div v-if="item.showButton">
              <el-icon @click.stop="editButton(item)"><Edit /></el-icon>
              <el-icon @click.stop="itemClickDelete(item)"><Delete /></el-icon>
            </div>
          </div>

        </el-menu-item>
        <el-input style="margin-left: 20px; width: 180px;" v-if="showAddInput" v-model="inputGroup" placeholder="请输入分组名" @blur="saveNewGroup">
          <template #append>
            <el-button type="info" @click="saveNewGroup">保存</el-button>
          </template>
        </el-input>
        <div style="margin-left: 20px;">
          <el-link type="primary" @click="showAddInput=true">新增分组</el-link>
        </div>
      </el-menu>
    </el-aside>
  </el-container>
</template>

<script lang="ts" setup name="sucai">
import { Search } from '@element-plus/icons-vue'
import {ArrowRight} from '@element-plus/icons-vue'
import {listImagetext,delImagetext} from '/@/api/publicaccount/imagetext'
import {listLinkuser,updateLinkuser} from '/@/api/publicaccount/linkuser'
import {listGroup,addGroup,updateGroup,delGroup} from  '/@/api/publicaccount/group'
import {onMounted, reactive, ref} from "vue";
import usePublicAccount from '/@/stores/modules/publicaccount'
import {useRouter} from "vue-router";
import {ElMessage} from "element-plus";

const publicAccount = usePublicAccount();
const total = ref(0);
const loading = ref(true);
const activeIndex = ref('4')
const tableData = ref([]);
const groupData = ref([]);
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  pusername: publicAccount.selectid,
  suborder: 0,
  status: 1,
  usergroup:'',
  searchName: ''
});

const baseImageUrl =import.meta.env.VITE_API_BASE_IMAGE_URL+'/imfiles/root/rainbowchatx/avatar/';
console.info("baseImageUrl:"+baseImageUrl);

function getList() {
  loading.value = true;
  listLinkuser(queryParams).then(response => {
    tableData.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

function getGroup(){
  const query = {
    pusername: publicAccount.selectid,
  }
  listGroup(query).then(rep =>{
    groupData.value = rep.rows;
  });
}

onMounted(() => {
  getList();
  getGroup();
})

function itemchange(groupId,item){
  console.info("itemchange",item,"groupId",groupId);
  const query = {
    username: item.username,
    pusername: publicAccount.selectid,
    usergroup: groupId
  }
  updateLinkuser(query).then(resp =>{
    getList();
    getGroup();
    ElMessage({
      type:'success',
      message: '放入分组成功'
    })
  })
}

const router = useRouter();
const handleUpdate = (item) => {
  if(item.type===0) {
    router.push('/publicAccountManager/tuwen?id=' + item.id);
  }else{
    router.push('/publicAccountManager/duotuwen?pid=' + item.pid);
  }
}


const deleteItem = (item) => {

}




const handleSelect = (key: string, keyPath: string[]) => {
  console.info("key",key);
  if (key) {
    queryParams.usergroup = groupData.value[key].id;
    getList();
  }
}

const handleSizeChange = (val: number) => {
  getList()
}
const handleCurrentChange = (val: number) => {
  getList()
}

function menuItemMouseEnter(item){
  if(item.mutable === 1) {
    if(!item.showEdit) {
      item.showButton = true;
    }
  }
}

function menuItemBlur(item) {
  if(item.mutable === 1) {
    item.showButton = false;
  }
}


function itemClickDelete(item) {
  console.info("itemClickDelete",item);
  delGroup(item.id,item.pusername).then(resp=>{
    item.showButton = false;
    getGroup();
    getList();
  })
}

function updateNewGroup(item) {
  console.info("updateNewGroup",item);
  updateGroup(item).then(resp=>{
    ElMessage({
      type:'success',
      message:'分组名称修改成功'
    });
    item.showEdit=false;
    getList();
    getGroup();
  })
}

function editButton(item) {
  item.showEdit=true;
  item.showButton=false;
}



function saveNewGroup(){
  if(groupData.value.length >=6 ){
    ElMessage({
      type:'warning',
      message:'已超过最大分组数量'
    });
    showAddInput.value=false;
    return;
  }
  if(inputGroup.value.trim() ===''){
    ElMessage({
      type:'warning',
      message:'请输入分组名称'
    });
    return;
  }
  const addParam={
    name: inputGroup.value,
    pusername: publicAccount.selectid,
    mutable: 1,
    membersSize:0,
  }
  addGroup(addParam).then(resp =>{
    ElMessage({
      type:'success',
      message:'添加分组成功'
    });
    getGroup();
    getList();
    showAddInput.value=false;
  });
}


const showAddInput = ref(false);
const inputGroup = ref('');
const small = ref(false)
const background = ref(false)
const disabled = ref(false)
</script>

<style scoped lang="scss">
.page-div {
  margin-top: 20px;
  text-align: center;
  display: flex;
  align-items: center;
  justify-content: center;
}
</style>
